package com.zhuizikejithreeig.cn.threeigkeji.mianinfo;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.zhuizikejithreeig.cn.adapter.LaYaListAdapter;
import com.zhuizikejithreeig.cn.been.LanYaBeen;
import com.zhuizikejithreeig.cn.braodcast.Bluetooth;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

public class ControlActivty extends BasicActivity implements View.OnClickListener, Bluetooth {

    private static final int REQUEST_ACCESS_COARSE_LOCATION = 203;
    private static final int READLOCATON = 204;
    private Button lanya;
    private Button start;
    private Button stop;
    private Button lanyastart;
    private Button lanyastop;
    private BluetoothAdapter mBluetoothAdapter;//蓝牙适配器
    private RecyclerView recycleview;
    private BluetoothClient mClient;
    private Set<String > nameSet = new HashSet();
    private List<LanYaBeen> list = new ArrayList<>();
    private List<LanYaBeen> newlist = new ArrayList<>();
    private LaYaListAdapter adapter;
    public static Bluetooth bluetooth;
    private boolean boolthConectListion = false;
    private boolean hasLanYaPermission=false;
    private static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    private String uri = "ws://192.168.0.200:1990";
    private WebSocketClient client;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_control_activty);
//        showBody();
        setLeftShow(1, R.mipmap.back);
        getLift_V().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        lanya = (Button) findViewById(R.id.lanya);
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);
        lanyastart = (Button) findViewById(R.id.lanyastart);
        lanyastop = (Button) findViewById(R.id.lanyastop);
        recycleview = (RecyclerView) findViewById(R.id.recycleview);
        LinearLayoutManager manager = new LinearLayoutManager(ControlActivty.this);
        recycleview.setLayoutManager(manager);

        lanya.setOnClickListener(this);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        lanyastart.setOnClickListener(this);
        lanyastop.setOnClickListener(this);
        bluetooth = this;
        hasPermission();

        try {
            instartSocket();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        //初始化蓝牙
        mClient = new BluetoothClient(ControlActivty.this);
    }



    private void hasPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            hasLanYaPermission = false;
            //判断是否有权限
            if (ContextCompat.checkSelfPermission(ControlActivty.this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //请求权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        REQUEST_ACCESS_COARSE_LOCATION);
                //向用户解释，为什么要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.READ_CONTACTS)) {
                    ToastMake.showToast("自Android 6.0开始需要打开位置权限才可以搜索到Ble设备");

                }
                hasReadPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
        }else {
            hasLanYaPermission = true;


        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //蓝牙开启
            case R.id.lanya:

                if (CheckBluetooth())
                    return;
                //3蓝牙设备已经开启
                if (ContextCompat.checkSelfPermission(ControlActivty.this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    hasReadPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
                    return;
                }

                final SearchRequest request = new SearchRequest.Builder()
                        .searchBluetoothLeDevice(3000, 1)   // 先扫BLE设备3次，每次3s
                        .searchBluetoothClassicDevice(5000) // 再扫经典蓝牙5s
                        .searchBluetoothLeDevice(2000)      // 再扫BLE设备2s
                        .build();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mClient.search(request, new SearchResponse() {
                            //蓝牙开始搜索的时候
                            @Override
                            public void onSearchStarted() {
                                showProgrees("蓝牙搜索中");
                                nameSet.clear();
                            }

                            //发现蓝牙的时候
                            @Override
                            public void onDeviceFounded(SearchResult device) {
                                Beacon beacon = new Beacon(device.scanRecord);
//                        System.out.println(String.format("beacon for %s\n%s", device.getAddress(), beacon.toString()));
                                //用been将其封装起来
//                                BluetoothDevice



                                if (device.getAddress() != null) {
                                    nameSet.add(device.getAddress()+"&"+device.getName());

                                }

                            }

                            //搜素停止的时候
                            @Override
                            public void onSearchStopped() {
                                hideProgree();
                                String mac = getConnectBt();
                                //当搜索到蓝牙为空的时候,继续搜索
                                if (!nameSet.isEmpty()) {
                                    list.clear();
                                    for (String  s : nameSet) {
                                        String[] split = s.split("&");
                                        LanYaBeen been = new LanYaBeen();
                                        been.setPostion(split[0]);
                                        if (TextUtils.equals(split[1],"NULL")){
                                            been.setName(split[0]);
                                        }else {
                                            been.setName(split[1]);
                                        }
                                        if (TextUtils.equals(split[0],mac)) {
                                            been.setCencent(true);
                                        }
                                        list.add(been);
                                    }
                                    Utils.runOnUIThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (adapter == null) {
                                                adapter = new LaYaListAdapter(list);
                                                recycleview.setAdapter(adapter);
                                            } else {
                                                adapter.notifyDataSetChanged();
                                            }
                                        }
                                    });


                                }

                            }

                            //搜素取消的时候
                            @Override
                            public void onSearchCanceled() {
                                hideProgree();
                            }
                        });

                    }
                }).start();


                break;
            //Scorket播放开始
            case R.id.start:

                break;
            //Scorkt播放结束
            case R.id.stop:
                break;
            //蓝牙控制开始
            case R.id.lanyastart:
//                if (boolthConectListion&&conectMac!=null) {
//
//                }
                break;
            //蓝牙控制结束
            case R.id.lanyastop:
                if (boolthConectListion) {

                }
                break;
        }
    }

    private void instartSocket() throws URISyntaxException {
       client = new WebSocketClient(new URI( uri )) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                System.out.println("Sockect连接已经打开");
                client.send("123");
            }

            @Override
            public void onMessage(String message) {

            }

            @Override
            public void onClose(int code, String reason, boolean remote) {

            }

            @Override
            public void onError(Exception ex) {

            }
        };
        client.connect();
    }

    //TODO:此方法为获取当前已经连接的设备
    private boolean CheckBluetooth() {
        if (mBluetoothAdapter == null) {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        //1.设备不支持蓝牙，结束应用
        if (mBluetoothAdapter == null) {
            ToastMake.showToast("该设备不支持蓝牙");
            return true;
        }
        //2.判断蓝牙是否打开
        //true表示已经开启，false表示蓝牙并没启用
        if (!mBluetoothAdapter.enable()) {
            mClient.openBluetooth();
        }
        return false;
    }



    private void hasReadPermission(String permission) {
        PermissionGen.with(ControlActivty.this)
                .addRequestCode(READLOCATON)
                .permissions(
                        permission
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = READLOCATON)
    public void requestPhotoSuccess() {
        //成功之后的处理
        //.......
        hasLanYaPermission = true;
    }

    @PermissionFail(requestCode = READLOCATON)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面
        hasLanYaPermission = false;
        ToastMake.showToast("读取蓝牙需要定位权限");
        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(ControlActivty.this, Manifest.permission.ACCESS_COARSE_LOCATION);
        if (!showRequestPermission) {
            Intent intent = new Intent(
                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }
    }
    //TODO:当点击某个条目时.创建连接
    @Override
    public void sendUri(final String uri) {
//        BluetoothDevice btDev = mBluetoothAdapter.getRemoteDevice(uri);
//        //开始配对
//        if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
//            Method createBondMethod = null;
//            try {
//                createBondMethod = BluetoothDevice.class.getMethod("createBond");
//                Boolean returnValue = (Boolean) createBondMethod.invoke(btDev);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//            //开始连接
//        }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
//
//            connect(btDev);
//
//        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                showProgrees("蓝牙连接中....");
                final String mac = getConnectBt();
                BleConnectOptions options = new BleConnectOptions.Builder()
                        .setConnectRetry(3)   // 连接如果失败重试3次
                        .setConnectTimeout(3000)   // 连接超时30s
                        .setServiceDiscoverRetry(3)  // 发现服务如果失败重试3次
                        .setServiceDiscoverTimeout(2000)  // 发现服务超时20s
                        .build();

                mClient.connect(uri, options, new BleConnectResponse() {
                    @Override
                    public void onResponse(int code, BleGattProfile data) {
                        hideProgree();
                        //如果连接成功
                        if (code == REQUEST_SUCCESS) {
                            System.out.println("连接成功");
                            newlist.clear();
                            for (LanYaBeen yaBeen : list) {
                                yaBeen.setCencent(false);
                                if (yaBeen.getPostion().equals(mac)) {
                                    yaBeen.setCencent(true);
                                }
                                newlist.add(yaBeen);
                            }
                            //再改变条目按钮的颜色
                            list.clear();
                            list.addAll(newlist);

                            Utils.runOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (adapter == null) {
                                        adapter = new LaYaListAdapter(list);
                                        recycleview.setAdapter(adapter);
                                    } else {
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                            });

                        } else {
                            System.out.println("连接失败");
                            newlist.clear();
                            for (LanYaBeen yaBeen : list) {
                                yaBeen.setCencent(false);
                                if (yaBeen.getPostion().equals(mac)) {
                                    yaBeen.setCencent(true);
                                }
                                newlist.add(yaBeen);
                            }
                            //再改变条目按钮的颜色
                            list.clear();
                            list.addAll(newlist);
                            Utils.runOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (adapter == null) {
                                        adapter = new LaYaListAdapter(list);
                                        recycleview.setAdapter(adapter);
                                    } else {
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                            });

                            ToastMake.showToast("蓝牙连接失败");
                        }
                    }
                });
            }
        }).start();

    }

    //检查已连接的蓝牙设备
    private String  getConnectBt() {
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
        try {//得到蓝牙状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);
            int state = (int) method.invoke(mBluetoothAdapter, (Object[]) null);

            if (state == BluetoothAdapter.STATE_CONNECTED) {

//                LogUtil.i("BluetoothAdapter.STATE_CONNECTED");

                Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
//                LogUtil.i("devices:"+devices.size());

                for (BluetoothDevice device : devices) {

                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);

                    if (isConnected) {
//                        LogUtil.i("connected:"+device.getAddress());
                        return device.getAddress();
                    }else {
                        ToastMake.showToast(getResources().getString(R.string.string57));}

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private void connect(BluetoothDevice btDev) {
        UUID uuid = UUID.fromString(SPP_UUID);
        try {
            BluetoothSocket btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
            btSocket.connect();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
